import qs from 'qs';
import axios from 'axios';
const baseUrl = process.env.NODE_ENV == "development" ? '/dev' : 'localhost';

function getType(type = "json") {
  let typeList = {
    form: "application/x-www-form-urlencoded",
    file: "multipart/form-data",
    json: "application/json"
  }
  type = type in typeList ? type : "json";
  return { typeName: type, typeVal: typeList[type] }
}

function parse(params, config = {}) {
  let { requestType, headers } = config;
  let contextType = headers && headers["content-type"] ? headers["content-type"] : "";
  let { typeName, typeVal } = getType(requestType || contextType),
    data = params, options;


  if (typeName == "form") {
    data = qs.stringify(params);
  } else if (typeName == "file") {
    data = new FormData();
    for (let i in params) {
      data.append(i, params[i])
    }
  }

  delete config["requestType"];
  options = config;
  options["headers"] = {
    "content-type": typeVal
  }
  serve.defaults.headers['Content-Type'] = typeVal

  return { data, options };
}

const serve = axios.create(
  {
    baseURL: baseUrl,
    timeout: 5000,
    responseType: "json",
    // 是否携带cookie
    withCredentials: false,
  }
)

serve.interceptors.request.use(beforeRequest, beforeRequestError);
serve.interceptors.response.use(beforeResponse, responseError);

export function get(url, paramList, configList) {
  let { data, options } = parse(paramList, configList);

  return serve.get(url, { params: data, ...options })
}

export function del(url, paramList, configList) {
  let { data, options } = parse(paramList, configList);
  return serve.delete(url, { params: data, ...options })
}

export function post(url, paramList, configList) {
  let { data, options } = parse(paramList, configList);
  return serve.post(url, data, { ...options });
}

export function put(url, paramList, configList) {
  let { data, options } = parse(paramList, configList);
  return serve.put(url, data, { ...options })
}


function beforeRequest(config) { return config; }

function beforeRequestError(error) { }

function beforeResponse(response) { return response; }

function responseError(error) { }








